package org.jeecgframework.codegenerate.generate.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.jeecgframework.codegenerate.config.DbConfig;
import org.jeecgframework.codegenerate.generate.TemplateConfig;
import org.jeecgframework.codegenerate.util.FileUtils;
import org.jeecgframework.codegenerate.util.NonceUtils;
import org.jeecgframework.codegenerate.util.TemplateConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.hutool.core.util.StrUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;

public class CodeGenerate {
	private static final Logger logger = LoggerFactory.getLogger(CodeGenerate.class);
	private static final String b = "__";
	protected List<String> msgs = new ArrayList();

	protected void loadTemplates(TemplateConfig templateConfig, String var2, Map<String, Object> data) throws Exception {
		for (int i = 0; i < templateConfig.getTemplateRootDirs().size(); ++i) {
			File templateRootDir = templateConfig.getTemplateRootDirs().get(i);
			this.loadTemplate(var2, templateRootDir, data, templateConfig);
		}

	}

	protected void loadTemplate(String var1, File templateRootDir, Map<String, Object> var3, TemplateConfig templateConfig) throws Exception {
		if (templateRootDir == null) {
			throw new IllegalStateException("'templateRootDir' must be not null");
		} else {
			logger.info("  load template from templateRootDir = '" + templateRootDir.getAbsolutePath() + "',stylePath ='" + templateConfig.getStylePath() + "',  out GenerateRootDir:" + DbConfig.getProjectPath());
			List<File> files = FileUtils.getFiles(templateRootDir);
			for (int i = 0; i < files.size(); ++i) {
				this.generateTemplates(var1, templateRootDir, var3, files.get(i), templateConfig);
			}

		}
	}

	protected void generateTemplates(String var1, File file1, Map<String, Object> var3, File file, TemplateConfig templateConfig) throws Exception {
		String absolutePath = FileUtils.getFileAbsolutePath(file1, file);
		try {
			if (templateConfig.getStylePath() != null && !"".equals(templateConfig.getStylePath()) && !absolutePath.replace(File.separator, ".").startsWith(templateConfig.getStylePath())) {
				return;
			}
			String var7 = a(var3, absolutePath, templateConfig);
			String var8;
			if (var7.startsWith("java")) {
				var8 = var1 + File.separator + DbConfig.sourceRootPackage.replace(".", File.separator);
				var7 = var7.substring("java".length());
				var7 = var8 + var7;
				this.generateTemplate(absolutePath, var7, var3, templateConfig);
			} else if (var7.startsWith("webapp")) {
				var8 = var1 + File.separator + DbConfig.webrootPackage.replace(".", File.separator);
				var7 = var7.substring("webapp".length());
				var7 = var8 + var7;
				this.generateTemplate(absolutePath, var7, var3, templateConfig);
			}
		} catch (Exception var10) {
			logger.error(var10.toString(), var10);
		}

	}

	protected void generateTemplate(String templateName, String fileName, Map<String, Object> var3, TemplateConfig templateConfig) throws Exception {
		if (fileName.endsWith("i")) {
			fileName = fileName.substring(0, fileName.length() - 1);
		}

		boolean var5 = NonceUtils.a(fileName);
		if (fileName.contains("__") && !var5) {
			fileName = fileName.replace("__", ".");
		}

		if (fileName.endsWith(".vue")) {
			fileName = fileName.substring(0, fileName.length() - 4);
		}

		if (!fileName.contains("vue") || templateConfig == null || StrUtil.isNotEmpty(templateConfig.getVueStyle()) || fileName.contains(templateConfig.getVueStyle() + File.separator)) {
			Template template = this.getTemplate(templateName, templateConfig);
			template.setOutputEncoding("UTF-8");
			File file = FileUtils.file(fileName);
			logger.info("[generate]\t template:" + templateName + " ==> " + fileName);
			TemplateConfiguration.write(template, var3, file,  "UTF-8");
			if (!this.getFileName(file)) {
				this.msgs.add("生成成功：" + fileName);
			}
			if (this.getFileName(file)) {
				this.writeTemplate(file, "#segment#");
			}

		}
	}

	protected Template getTemplate(String templateName, TemplateConfig templateConfig) throws IOException {
		return TemplateConfiguration.getConfiguration(templateConfig.getTemplateRootDirs(),"UTF-8", templateName).getTemplate(templateName);
	}

	protected boolean getFileName(File file) {
		return file.getName().startsWith("[1-n]");
	}

	protected void writeTemplate(File file, String var2) {
		List<OutputStreamWriter> var5 = new ArrayList<OutputStreamWriter>();
		int var28;
		try {
			InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file), "UTF-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			boolean var7 = false;
			OutputStreamWriter var8 = null;
			while (true) {
				String var6;
				while ((var6 = bufferedReader.readLine()) != null) {
					if (var6.trim().length() > 0 && var6.startsWith(var2)) {
						String var9 = var6.substring(var2.length());
						String var10 = file.getParentFile().getAbsolutePath();
						var9 = var10 + File.separator + var9;
						var8 = new OutputStreamWriter(new FileOutputStream(var9), "UTF-8");
						var5.add(var8);
						this.msgs.add("生成成功：" + var9);
						var7 = true;
					} else if (var7) {
						var8.append(var6 + "\r\n");
					}
				}

				for (int var29 = 0; var29 < var5.size(); ++var29) {
					((Writer) var5.get(var29)).close();
				}
				inputStreamReader.close();
				b(file);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected static String a(Map<String, Object> data, String var1, TemplateConfig templateConfig) throws Exception {
		String var3 = var1;
		boolean var4 = true;
		int index = var1.indexOf(64);
		if (index != -1) {
			var3 = var1.substring(0, index);
			String var5 = var1.substring(index + 1);
			Object var6 = data.get(var5);
			if (var6 == null) {
				System.err.println("[not-generate] WARN: test expression is null by key:[" + var5 + "] on template:[" + var1 + "]");
				return null;
			}
			if (!"true".equals(String.valueOf(var6))) {
				logger.error("[not-generate]\t test expression '@" + var5 + "' is false,template:" + var1);
				return null;
			}
		}

		Configuration configuration = TemplateConfiguration.getConfiguration(templateConfig.getTemplateRootDirs(),"UTF-8", "/");
		var3 =TemplateConfiguration.processTemplate(var3, data, configuration);
		String var11 = templateConfig.getStylePath();
		if (var11 != null && var11 != "") {
			var3 = var3.substring(var11.length() + 1);
		}

		String var7 = var3.substring(var3.lastIndexOf("."));
		String var8 = var3.substring(0, var3.lastIndexOf(".")).replace(".", File.separator);
		var3 = var8 + var7;
		return var3;
	}

	protected static boolean b(File var0) {
		boolean var1 = false;

		for (int var2 = 0; !var1 && var2++ < 10; var1 = var0.delete()) {
			System.gc();
		}

		return var1;
	}

	protected static String a(String var0, String var1) {
		boolean var2 = true;
		boolean var3 = true;

		do {
			int var4 = var0.indexOf(var1) == 0 ? 1 : 0;
			int var5 = var0.lastIndexOf(var1) + 1 == var0.length() ? var0.lastIndexOf(var1) : var0.length();
			var0 = var0.substring(var4, var5);
			var2 = var0.indexOf(var1) == 0;
			var3 = var0.lastIndexOf(var1) + 1 == var0.length();
		} while (var2 || var3);

		return var0;
	}
}
